package com.example.demo.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.demo.config.AlipayConfig;
import com.example.demo.pojo.Dto.OrderCDto;
import com.example.demo.pojo.Dto.OrderDto;
import com.example.demo.pojo.Order;
import com.example.demo.service.OrderService;
import com.example.demo.utill.ResponseResult;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrderService orderService;

    @RequestMapping("/orderAll")
    @ResponseBody
    public ResponseResult selectOrderAll(HttpSession session){
        ResponseResult res=new ResponseResult();
        int uid=(int)session.getAttribute("userId");
        Map<String,Object> map=orderService.selectOderAll(uid);
        res.setCode(200);
        res.setData(map);
        return res;
    }

    @RequestMapping("/orders")
    @ResponseBody
    public PageInfo selectOrder(HttpSession session,
                                @RequestParam(value = "pageNum",required = false,defaultValue = "1")int pageNum,
                                @RequestParam(value = "pageSize",required = false,defaultValue = "6")int pageSize){
        int uid=(int)session.getAttribute("userId");
        return orderService.selectOrder(uid,pageNum,pageSize);
    }

    @RequestMapping("/orderParam")
    @ResponseBody
    public List<Integer> selectOrderParam(HttpSession session){
        int uid=(int)session.getAttribute("userId");
        List<Integer> list=orderService.selectOrderParam(uid);
        return list;
    }

    @RequestMapping("/byOrderNo")
    @ResponseBody
    public Order selectByOrderNo(String orderNo){
        Order order=orderService.selectByOrderNo(orderNo);
        return order;
    }

    @RequestMapping("/orderItem")
    @ResponseBody
    public List<OrderDto> selectOrderItem(int id){
        List<OrderDto> orderDto=orderService.selectOrderItem(id);
        return orderDto;
    }

    @RequestMapping("/cancelOrder")
    @ResponseBody
    public ResponseResult cancelOrder(String orderno){
        ResponseResult res=new ResponseResult();
        orderService.cancelOrder(orderno);
        res.setCode(200);
        return res;
    }

    @RequestMapping("/makeOrder")
    @ResponseBody
    public ResponseResult makeOrder(int[] ids,Order order,HttpSession session){
        ResponseResult res=new ResponseResult();
        int uid=(int)session.getAttribute("userId");
        order.setUserid(uid);
        res.setCode(200);
        OrderCDto orderCDto=orderService.insertOrder(ids,order);
        res.setData(orderCDto);
        return res;
    }

    @RequestMapping("/pay")
    @ResponseBody
    public String pay(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
        String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
        //订单名称，必填
        String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
        //商品描述，可空
        String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //设置响应内容类型
        //response.setContentType("text/html;charset=UTF-8");
        //输出
        //response.getWriter().println(result);
        return  result;
    }

    @RequestMapping("/update")
    public void update(HttpServletRequest request,HttpServletResponse response)throws Exception{
        System.out.println("进入");
        Map<String,String> params = new HashMap<String, String>();
        System.out.println(params);
        Map<String,String[]> requestParams = request.getParameterMap();
        System.out.println(requestParams);
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            System.out.println(values);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            System.out.println(valueStr);
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        System.out.println(signVerified);
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            System.out.println("----");
            //调用service实现修改订单状态
            orderService.update(out_trade_no);

            response.getWriter().println("success");

        }else {//验证失败
            response.getWriter().println("fail");
            System.out.println("++++++");
            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }
}
